<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="预约时间" value="appointmentDt" />
          <el-option label="下单时间" value="transactTime" />
          <el-option label="催单时间" value="lastUrgeDt" />
          <el-option label="签收时间" value="signTime" />
        </el-select>
        <el-date-picker
          v-show="dateType==='appointmentDt'"
          v-model="date1"
          type="date"
          :picker-options="pickerOptions"
          unlink-panels
          :clearable="false"
        />
        <el-date-picker
          v-show="dateType!=='appointmentDt'"
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="orderCode" label="订单号" />
          <el-option value="contactPhone" label="客户电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmAddress" label="客户地址" />
          <el-option value="remark" label="备注" />
          <el-option value="goodsDesc" label="商品描述" />
          <!-- <el-option value="saleMan" label="销售员" /> -->
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="催单来源:">
        <el-select v-model="query.orderSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select
          v-model="query.csmTypeSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态:">
        <el-select
          v-model="query.orderStatusSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
          @select-clear="orgClear"
        />
      </el-form-item>

      <el-form-item class="merge-item">
        <el-select
          v-model="user_qtype"
          style="width: 170px; margin-right: 2px;"
          @change="qtypeChange"
        >
          <el-option value="ownerIdList" label="处理人" />
          <el-option value="transactIdList" label="下单人" />
        </el-select>
        <el-select
          v-model="user_qtype_value"
          :loading="$loadingPlugin.getOwnerList || $loadingPlugin.getTransactorList"
          filterable
          clearable
          multiple
          collapse-tags
          placeholder="请选择"
        >
          <el-option
            v-for="item in userQtypeList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="超时状态:">
        <el-select v-model="query.overTimeType" clearable>
          <el-option label="超时预警" :value="1" />
          <el-option label="已超时" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="转派状态:">
        <el-select v-model="query.isTransfer" clearable>
          <el-option label="全部" :value="0" />
          <el-option label="待转派" :value="1" />
          <el-option label="已转派" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[40106, 1]"
          :loading="$loadingPlugin.fetchData"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="[40106, 3]"
          :loading="$loadingPlugin.exportFile"
          type="primary"
          icon="el-icon-download"
          @click="exportFile(0)"
        >导出</el-button>
        <!-- <el-button v-permission="16" type="primary" icon="el-icon-download" @click="exportFile(1)">非脱敏导出</el-button> -->
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      :immediate-fetch="false"
      default-open
      @fetch="fetchData"
    />
    <csm-location ref="csmLocation" />
    <csm-detail ref="csmDetail" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymentMethodMap" :parent-fetch-data="search" />
    <order-images ref="orderImages" />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
    <pay-detail ref="payDetail" :payment-method-map="paymentMethodMap" />
    <transfer-order ref="transferOrder" />
  </div>
</template>

<script>
  import {
    csDeliverUserList,
    queryTransactorList,
    queryMap,
    queryExportDomain,
    batchUserOrder,
    orderBillUrgeList,
    orderBillUrgeExport
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { orderStatusObj, payStatusObj } from '@/utils/map'
  import CsmLocation from '../../../components/CsmLocation'
  import OrderImages from './OrderImages'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import OrderDetail from './OrderDetails'
  import PayDetail from './PayDetail'
  import TransferOrder from '../../../components/TransferOrderModal'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { minDate } from '@/utils/config'

  export default {
    components: {
      CsmLocation,
      OrderImages,
      CsmDetail,
      OrderDetail,
      PayDetail,
      TransferOrder
    },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return moment(time.getTime()).diff(moment(Date.now()), 'days') < 0
          }
        },
        actionColWidth: 80,
        treeData: [],
        currentOrg: null,
        ownerList: [],
        transactorList: [],
        qtype: 'contactPhone',
        txt: '',
        orderSourceMap: [],
        orderFlagMap: [],
        user_qtype: 'ownerIdList',
        user_qtype_value: '',
        userQtypeList: [], // 下单人或处理人列表
        dateType: 'lastUrgeDt',
        date: [moment().startOf('day'), moment().endOf('day')],
        date1: parseTime(Date.now(), '{y}-{m}-{d}'),
        orderStatusMap: [],
        customerTypeMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        reStatusMap: [],
        calcTypeList: [],
        searchParams: {},
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          orderSource: [0],
          orderFlagSource: [0],
          isRemedy: '',
          orderStatusSource: [1, 2, 5],
          csmTypeSource: [0],
          payStatus: '',
          paymentMethodSource: [0],
          reStatus: '',
          overTimeType: '',
          ownerIdList: [],
          isTransfer: 0
        },
        roleTypeList: [],
        userList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            fixed: 'left'
          },
          {
            prop: 'orderCode',
            label: '订单号',
            width: 110,
            fixed: 'left',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openOrderDetail(row)}>
              {row.orderCode}
            </el-link>
          )
          },
          {
            prop: 'urgeCount',
            label: '催单次数',
            width: 120,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(3, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(3, 2)}></i></span>
            },
            render: (h, { row }) => (
          <span style={(row.urgeCount > 1 && row.orderStatus !== 10) ? 'color:red;' : '' }>{ row.urgeCount }</span>
          )
          },
          {
            prop: 'fromPlat',
            label: '催单来源',
            minWidth: 110,
            render: (h, { row }) => (
            <span>
              {row.fromPlat &&
                formatColumnMap(this.orderSourceMap, 'value', row.fromPlat, 'desc')}
            </span>
          )
          },
          {
            prop: 'signDt',
            label: '签收时间',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.signDt &&
                new Date(row.signDt).getTime() >= new Date(minDate).getTime() &&
                parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'overTimeType',
            label: '超时状态',
            width: 100,
            render: (h, { row }) => (
            <span class={row.overTimeType === 1 ? 'yellow' : 'red'} onClick={() => this.showTimeoutDetails(row)}>
              {row.overTimeType === 0 ? '' : row.overTimeType === 1 ? '超时预警' : row.overTimeType === 2 ? '已超时' : ''}
            </span>
            )
          },
          {
            prop: 'ownerName',
            label: '处理人',
            showOverflowTooltip: true
          },
          {
            prop: 'driverName',
            label: '大车司机',
            showOverflowTooltip: true
          },
          {
            prop: 'escortName',
            label: '押运员',
            showOverflowTooltip: true
          },
          {
            prop: 'orderStatus',
            label: '订单状态',
            render: (h, { row }) => (
            <span style={orderStatusObj[row.orderStatus]}>
              {row.orderStatus &&
                formatColumnMap(this.orderStatusMap, 'value', row.orderStatus, 'desc')}
            </span>
          )
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>

          },
          {
            prop: 'csmName',
            label: '客户名称',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>
              {row.csmName}
            </el-link>
          )
          },
          {
            prop: 'contactPhone',
            label: '客户电话',
            width: 130,
            render: (h, { row }) => {
              if (row.contactPhone) {
                return (
                <span>
                  <svg-icon icon-class='call' onClick={e => window.pbx.dial(row.contactPhone, e)} />{row.contactPhone}
                </span>
              )
              }
              return ''
            }
          },
          {
            prop: 'csmAddress',
            label: '联系地址',
            width: 220,
            render: (h, { row }) => {
              return (
              <span>
                <span class='point-span'>
                  {this.$btnPermission([40106, 4]) && row.lon && row.lat && (
                    <i
                      onClick={() => this.openLocation(row)}
                      class='linkColor el-icon-location'
                      style='cursor: pointer;'
                    />
                  )}
                  {!this.$btnPermission([40106, 4]) && (
                    <i class='el-icon-location' style='color:#126edc;cursor: pointer;' />
                  )}
                </span>
                <span>{row.csmAddress}</span>
              </span>
              )
            }
          },
          {
            prop: 'appointmentDt',
            label: '预约时间',
            minWidth: 200,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(2, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(2, 2)}></i></span>
            },
            render: (h, { row }) => {
              return (
                <div class={this.getClass(row)}>
                  {(row.appointmentDt && row.dateTimeSpare1) && <span>{parseTime(row.dateTimeSpare1, '{h}:{i}') === '23:59' ? parseTime(row.appointmentDt, '{y}-{m}-{d}') : parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(row.dateTimeSpare1, '{h}:{i}')}</span>}
                </div>
              )
            }
          },
          {
            prop: 'overTimeStr',
            label: '超时时间',
            showOverflowTooltip: true
          },
          {
            prop: 'lastUrgeDt',
            label: '催单时间',
            width: 140,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(1, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(1, 2)}></i></span>
            },
            render: (h, { row }) => (
            <span>
              {row.lastUrgeDt && parseTime(row.lastUrgeDt, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 160
          },
          {
            prop: 'transactor',
            label: '下单人'
          },

          {
            prop: 'goodsDesc',
            label: '商品描述',
            width: 150
          },

          {
            prop: 'decimalSpare4',
            label: '订单总额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.decimalSpare4 && row.decimalSpare4.toFixed(2)}
            </el-link>
          )
          },

          {
            prop: 'distance',
            label: '配送距离(km)',
            align: 'center',
            width: 110,
            render: (h, { row }) => (
            <span>{row.distance && (row.distance / 1000).toFixed(2)}</span>
          )
          },

          {
            prop: 'taccReceivable',
            label: '实收金额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.taccReceivable && row.taccReceivable.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'payStatus',
            label: '支付状态',
            render: (h, { row }) => (
            <span style={payStatusObj[row.payStatus]}>
              {row.payStatus
                ? formatColumnMap(this.payStatusMap, 'value', row.payStatus, 'desc')
                : '未支付'}
            </span>
          )
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => (
            <span>
              {row.paymentMethod &&
                formatColumnMap(
                  this.paymentMethodMap,
                  'value',
                  row.paymentMethod,
                  'desc'
                )}
            </span>
          )
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (row.orderStatus === 2) && (
             <el-button v-permission='[40106, 2]' onClick={() => this.openTransferOrder(row, $index)} type='text'>转派</el-button>
              )
            }
          }
        ]
      }
    },
    watch: {
      'query.orderSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderSource.length === this.orderSourceMap.length) {
          this.query.orderSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderFlagSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderFlagSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderFlagSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderFlagSource.length === this.orderFlagMap.length) {
          this.query.orderFlagSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderStatusSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderStatusSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderStatusSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderStatusSource.length === this.orderStatusMap.length) {
          this.query.orderStatusSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.csmTypeSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.csmTypeSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.csmTypeSource.splice(val.indexOf(0), 1)
        }
        if (this.query.csmTypeSource.length === this.customerTypeMap.length) {
          this.query.csmTypeSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.paymentMethodSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.paymentMethodSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.paymentMethodSource.splice(val.indexOf(0), 1)
        }
        if (this.query.paymentMethodSource.length === this.paymentMethodMap.length) {
          this.query.paymentMethodSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      $route: {
        handler: function(to, from) {
          this.reGetUrlParams()
        },
        deep: true
      }
    },
    async created() {
      await Promise.all([
        this.getExportDomain(),
        this.getTreeData(),
        // this.getTransactorList(),
        // this.getOwnerList(),
        this.queryOptionsMap()
      ])
      this.qtypeChange('ownerIdList')
    },
    methods: {
      reGetUrlParams() {
        if (this.$route.query) {
          const urlParams = this.$route.query
          this.query.isTransfer = urlParams.isTransfer ? Number(urlParams.isTransfer) : ''
          this.dateType = urlParams.dateType ? urlParams.dateType : 'lastUrgeDt'
        }
        this.search()
      },
      getClass(r) {
        if (r.overTimeType) {
          if (r.overTimeType === 1) {
            return 'yellow'
          }
          if (r.overTimeType === 2) {
            return 'red'
          }
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async getUserOrder() {
        this.query.ownerIdList = []
        const params = {
          orgSNNo: this.query.orgSNNo
        }
        const res = await batchUserOrder(params)
        this.userList = res.data
      },
      sortColumn(sortColumn, sortType) {
        this.query.sortColumn = sortColumn
        this.query.sortType = sortType
        this.search()
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        if (this.query.orderSource[0] === 0) query.orderSource = []
        query[this.user_qtype] = this.user_qtype_value
        if (this.query.orderFlagSource[0] === 0) query.orderFlagSource = []
        if (this.query.orderStatusSource[0] === 0) query.orderStatusSource = []
        if (this.query.csmTypeSource[0] === 0) query.csmTypeSource = []
        if (this.query.paymentMethodSource[0] === 0) query.paymentMethodSource = []
        if (this.date && this.date.length === 2) {
          if (this.dateType !== 'appointmentDt') {
            query[this.dateType] = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
            query[`${this.dateType}End`] = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        if (this.dateType === 'appointmentDt' && this.date1) {
          query.appointmentDt = moment(this.date1).format('YYYY-MM-DD') + ' 00:00:00'
          query.dateTimeSpare1 = moment(this.date1).format('YYYY-MM-DD') + ' 23:59:59'
        }
        const res = await orderBillUrgeList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.query.ownerIdList = []
        this.getOwnerList()
        // this.getUserOrder()
      },
      orgClear() {
        if (this.user_qtype === 'ownerIdList') {
          this.user_qtype_value = []
          this.userQtypeList = []
        }
        this.currentOrg = undefined
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7, res8] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderUrgeSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 4 && item.value !== 6 && item.value !== 8) // 订单类型(去掉‘已转派’“已接收”“已出库”)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 1024 || item.value === 2048) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
        this.calcTypeList = res8.data // 收款方式
      },
      // 配送距离数据格式化
      distanceFormat(v, r, i) {
        if (!Number(v)) {
          return ''
        }
        var msg = (Number(v) / 1000 || 0).toFixed(2)
        return msg
      },
      // 获取处理人列表
      async getOwnerList() {
        const orgId = this.currentOrg ? this.currentOrg.orgId : 0
        const orgSNNo = this.currentOrg ? this.currentOrg.orgSNNo : 0
        if (orgId) {
          const res = await csDeliverUserList({
            deliveryOrgId: orgId,
            deliveryOrgSNNo: orgSNNo
          })
          this.ownerList = res.data
        } else {
          this.ownerList = []
        }
        if (this.user_qtype === 'ownerIdList') {
          this.user_qtype_value = []
          this.userQtypeList = this.ownerList
        } else {
          this.userQtypeList = this.transactorList
        }
      },
      // 获取下单人列表
      async getTransactorList() {
        if (this.transactorList.length === 0) {
          const res = await queryTransactorList({})
          this.transactorList = res.data
        }
        if (this.user_qtype === 'ownerIdList') {
          this.userQtypeList = this.ownerList
        } else {
          this.userQtypeList = this.transactorList
        }
      },
      // 处理人或下单人选择
      async qtypeChange(value) {
        this.user_qtype_value = []
        if (value === 'ownerIdList') {
          await this.getOwnerList()
        } else {
          await this.getTransactorList()
        }
      },

      // 点击图片
      async showImage(row) {
        await this.$refs.orderImages.open(row)
      },
      // 点击地址
      async openLocation(row) {
        await this.$refs.csmLocation.open(row)
      },
      // 点击客户名称
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 点击订单号
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      // 点击订单总额
      async openPayDetail(row) {
        await this.$refs.payDetail.open(row)
      },

      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async scoresMerge() {
        await this.$refs.scoresMerge.open()
      },
      async infoCircul() {
        // 参数为订单号
        await this.$refs.infoCircul.open('176697')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 导出
      async exportFile(type) {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          params.tabType = 4
          params.desensitizeFlag = type
          orderBillUrgeExport({
            paramInfo: _this._getQuery(params),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7 || row.orderStatus === 3) {
          // 7:已退单 3:退单申请中
          return 'danger-row'
        }
        if (row.orderStatus === 9 || row.orderStatus === 12) {
          // 9:退货申请中 12:已退货
          return 'giveup-row'
        }
        return ''
      },
      async showTimeoutDetails(row) {
        this.$refs.orderDetail.open(row, 'overTime')
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffeced;
}
/deep/ .el-table tr.giveup-row {
  background: #ffeced;
}
/deep/.red {
  color: #f00 !important;
  cursor: pointer;
}
/deep/.yellow {
  color: #ed912e !important;
  cursor: pointer;
}
</style>
